from flask import abort
from flask import current_app
from flask import g
from flask import render_template
from flask import session

from info import constants, db
from info.models import User, News
from info.utils.commons import login_user_data
from . import news_blu
@news_blu.route('/<int:news_id>')
@login_user_data
def get_news_detail(news_id):
    # 尝试从session中获取user_id
    # user_id = session.get('user_id')  # 获取不到，返回None
    # user = None
    # if user_id:
    #     # 用户已登录
    #     try:
    #         # user = User.query.get(user_id)
    #         # user.avatar_url = constants.QINIU_DOMIN_PREFIX + user.avatar_url
    #         user = User.query.get(user_id)
    #         user.avatar_url = constants.QINIU_DOMIN_PREFIX + user.avatar_url
    #     except Exception as e:
    #         current_app.logger.error(e)

    user=g.user
    try:
        news=News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not news:
        abort(404)
    news.clicks +=1
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        




    return render_template('news/detail.html',
                            user=user,
                           news=news
                            )
